package com.gxa.component.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//自定义消费者 -- 消费消息 -- 监听接收消息
public class ConsumerMain {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // rabbitmq主机地址 = ip
        connectionFactory.setHost("121.4.166.75");
        // 通信端口5672 - 记得关闭防火墙
        connectionFactory.setPort(5672);
        // 虚拟主机地址
        connectionFactory.setVirtualHost("/");
        // 用户名
        connectionFactory.setUsername("gxa");
        // 密码
        connectionFactory.setPassword("123456");
        // 获取连接
        Connection connection = connectionFactory.newConnection();
        // 2.创建channel
        Channel channel = connection.createChannel();
        // 3.声明队列
        final  String QUEUE_NAME = "simple.queue";
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        // 4.监听接收消息
        channel.basicConsume(QUEUE_NAME,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body);
                System.out.println("消费者接收到的消息："+message);
            }
        });
        // 5.无需关闭连接和channel，因为消费一直处于监听状态


    }

}
